package com.example.accountservice.service;

import com.example.accountservice.dao.AccountMapper;
import com.example.accountservice.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * program: springcloud-seata
 * description:
 * author: Mr.Yiu
 * create: 2021-05-19 16:17
 **/
@Service
public class AccountService {
    @Autowired
    private AccountMapper accountMapper;

    public int add(String name, double money) {
        return accountMapper.add(name, money);
    }
    public int update(String name, double money, int id) {
        return accountMapper.update(name, money, id);
    }
    public int delete(int id) {
        return accountMapper.delete(id);
    }
    public Account findAccount(int id) {
        return accountMapper.findAccount(id);
    }
    public List<Account> findAccountList() {
        return accountMapper.findAccountList();
    }

    //扣减金额
    @Transactional
    public Map<String, Object> deductMoney(int id, double money){
        Map<String, Object> result = new HashMap<String, Object>();
        Account account = this.findAccount(id);
        if (account==null){
//            result.put("code", 1);
//            result.put("desc", "不存在用户");
//            return result;
            throw new RuntimeException("不存在用户");
        }

        if(account.getMoney()<money){
//            result.put("code", 11);
//            result.put("desc", "余额不足");
//            return result;
            throw new RuntimeException("余额不足");
        }

        int r = this.update(account.getName(),account.getMoney()-money,account.getId());
        if(r==1){
            result.put("code", 0);
            result.put("desc", "付款成功");
            return result;
        }

        return result;
    }
}
